package com.maple.sharding.config.sharding.user;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class DatabasePreciseShardingAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
        System.out.println("collection:" + JSONObject.toJSONString(collection) + ",shardingValues:" + JSONObject.toJSONString(preciseShardingValue));
        Collection<String> tables = collection;
        String shardingValue = getShardingValue(preciseShardingValue);
        return tables.stream().filter((table) -> table.endsWith(shardingValue)).findFirst().get();
    }

    /**
     * 获取倒数第3位
     *
     * @return
     */
    private String getShardingValue(PreciseShardingValue preciseShardingValue) {
        String tempShardingValue = String.valueOf(preciseShardingValue.getValue());
        return "0" + StringUtils.substring(tempShardingValue, tempShardingValue.length() - 3, tempShardingValue.length() - 2);
    }
}
